# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myFileUtil
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/17 10:23
@desc: 增加一个文件相关的写入读取，删除等相关处理
========================================================================================================================
"""
import os
import shutil

import aiofiles
from typing import AnyStr
import asyncio


class FileUtil:

    @staticmethod
    def check_path(file_path):
        return  file_path.__contains__('\\') or file_path.__contains__('/')

    @staticmethod
    async def fileDownload(data:bytes, file_path:AnyStr=None):
        """
        @Params: data 字节流
        @Params: filename 报错的文件名称
        @Params: forever 是否为永久文件
        @Params: exist_time 默认文件存在时间
        """
        # 判断是否只是文件名称
        threshold = FileUtil.check_path(file_path)

        if not threshold:
            raise Exception("file_path 不能为文件名")

        async with aiofiles.open(file_path, 'wb') as fp:
            await fp.write(data)

        return file_path

    @staticmethod
    def remove(file_path:AnyStr, error_ignore:bool=True):
        """
        @Params: file_path 删除文件或者文件夹
        @Params: error_ignore 是否报错
        """

        is_dir = os.path.isdir(file_path)

        try:
            if is_dir:
                shutil.rmtree(file_path)
            else:
                os.remove(file_path)
        except Exception as e:
            if not error_ignore:
                raise Exception("文件: %s 被其他进程占用" % file_path)




async def main():
    file_path = await FileUtil.fileDownload(b'asdadsasdadad', r'C:\Users\my\Desktop\vanke\1.pdf')
    FileUtil.remove(file_path, error_ignore=False)
    print("完成")


if __name__ == '__main__':
    asyncio.run(main())

